package com.cssl.gulimall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cssl.common.constant.member.MemberConstant;
import com.cssl.common.to.member.MemberUserLoginTO;
import com.cssl.common.to.member.MemberUserRegisterTO;
import com.cssl.common.vo.auth.GiteeUser;
import com.cssl.common.vo.auth.UserForgetVO;
import com.cssl.gulimall.member.entity.MemberEntity;
import com.cssl.gulimall.member.entity.MemberLevelEntity;
import com.cssl.gulimall.member.exception.PhoneException;
import com.cssl.gulimall.member.exception.UsernameException;
import com.cssl.gulimall.member.dao.MemberDao;
import com.cssl.gulimall.member.service.MemberLevelService;
import com.cssl.gulimall.member.service.MemberService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public void regist(MemberUserRegisterTO user) throws InterruptedException {
        //获取锁
        RLock lock = redissonClient.getLock(MemberConstant.LOCK_KEY_REGIST_PRE + user.getPhone());
        try {
            lock.tryLock(30L, TimeUnit.SECONDS);
            //校验
            checkPhoneUnique(user.getPhone());
            checkUserNameUnique(user.getUserName());
            //封装
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setUsername(user.getUserName());
            memberEntity.setMobile(user.getPhone());
            memberEntity.setNickname(user.getUserName());
            //设置默认等级
            MemberLevelEntity level = memberLevelService.getDefaultLevel();
            memberEntity.setLevelId(level.getId());
            //设置密码加密存储
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(user.getPassword());
            memberEntity.setPassword(encode);
            memberEntity.setCreateTime(new Date());
            this.baseMapper.insert(memberEntity);
        } finally {
            lock.unlock();;
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginTO user) {
        String loginacct = user.getLoginacct();
        String password = user.getPassword();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));
        if(entity!=null){
            //获取password密文进行校验
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if(encoder.matches(password, entity.getPassword())){
                //登录成功
                return entity;
            }
        }
        return null;
    }

    @Override
    public MemberEntity login(GiteeUser giteeUser){
        //登录和注册合并逻辑

        //具有登录和注册逻辑
        System.out.println("id  :" + giteeUser.getId());
        System.out.println("name  :" + giteeUser.getName());
        System.out.println("bio  :" + giteeUser.getBio());

        String uid = giteeUser.getId();

        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        System.out.println("memberEntity："+memberEntity);
        if (memberEntity != null) {
            //这个用户已经注册过
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setUsername(giteeUser.getName());
            this.baseMapper.updateById(update);

            memberEntity.setUsername(giteeUser.getName());
            return memberEntity;
        } else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();

            register.setCreateTime(new Date());
            register.setSocialUid(giteeUser.getId());
            register.setUsername(giteeUser.getName());
            register.setNickname(giteeUser.getName());


            //把用户信息插入到数据库中
            this.baseMapper.insert(register);


            return register;

        }
    }


    private void checkUserNameUnique(String userName) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(count>0){
            System.out.println("===用户名已存在");
            throw new UsernameException();
        }
    }

    private void checkPhoneUnique(String phone) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile",phone));
        if(count>0){
            System.out.println("===手机号被注册");
            throw new PhoneException();
        }
    }

    @Override
    public MemberEntity hasPhoneBiding(String phone) {
        return baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile",phone));
    }

    @Override
    public void changePwd(UserForgetVO userForgetVO) {
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile",userForgetVO.getPhone()));
        //设置密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(userForgetVO.getPassword());
        entity.setPassword(encode);
        baseMapper.updateById(entity);
    }
}
